/** 不要使用JQuery **/
var pageS = {};
pageS.isSubmitting = false;

var pageX = {
    postData : {
        attFileDomain : []//附件
    },
    fileComponent : null,
    wfDesigner : null,
    inputUsers : {},
    currentUser : null,
    contentDesigner : null,
    summary : null,
    defPolicy : null,
    importLevelEnum : null,
    isInitData : false,//标记是否完成数据加载
    contentHeight : 0,
    windowHeight : window.innerHeight,
    cache : {
       "isLightForm" : true
    }

};
var openFrom ="";
var cttId="";
var colMainDataDomain;
var params;
var _isContentInit = false;
var _storge_key = "m3_v5_collaboration_newCol_cache_key";
var hasPigeonholePolicy=true;
var hasloadingbar = true;

cmp.ready(function() {
	cmp.dialog.loading();
	cmp.backbutton();
    cmp.backbutton.push(_closePage);
    
  //退出
    _$("#closeBtn").addEventListener("tap", _closePage);
    
    
    cmp.i18n.init(_collPath + "/i18n/", "Collaboration", function(){
    	
        //国际化title标签
        _$("title").innerText=cmp.i18n("collaboration.page.lable.newCol");
        
        _initParamData();
        
        _initLayout();

        _initPageData();
        
        dealHeader();
    });
   
    document.addEventListener('beforepageredirect', function(e){ 
    	_storePageObj();
	});
});

function _initParamData() {
    /**
     * pageX.winParams = {
     *     subject : "",
     *     content : "",
     *     members : "",
     *     summaryId : "",//协同ID
     *     templateId : "",//模板ID
     *     openFrom ： "",
     *     preCaches : [],
     *     backIndex : 0
     * }
     */
	pageX.winParams = cmp.href.getParam() || {};
	
	if(CollUtils.isEmptyObj(pageX.winParams)){
	    
		pageX.winParams = CollUtils.getHrefQuery();
		
		if(pageX.winParams.subject) {
			pageX.winParams.subject = decodeURIComponent(pageX.winParams.subject);
		}
		if(pageX.winParams.content) {
			pageX.winParams.content = decodeURIComponent(pageX.winParams.content);
		}
		if(pageX.winParams.members) {
			pageX.winParams.members = decodeURIComponent(pageX.winParams.members);
		}
    }
	
    params = pageX.winParams;//关联表单要用的全局变量
}

/** 页面 **/
function _initLayout(){
    
  //标题宽度, 12px是标签之间的空格导致的
    _$("#subject_c").style.width = (_$("#receiver_li").clientWidth - 30 - 17 - _$("#coll_subject").offsetWidth) + "px";
    _$('#preDiv').style.width = _$("#subject_c").offsetWidth +"px";
    _$('#subject').style.width = _$("#subject_c").offsetWidth + "px";

    var w = (_$("#receiver_li").clientWidth
                - _$("#receiver_title").offsetWidth - 10
                - _$("#edit_receiver").offsetWidth) + "px";
    //接收人宽度计算
    _$("#receiver_container").style.width = w;
    _$("#receiver_container_text").style.width = w;

    //新建协同位置调整
    _$('.cmp-title').style.display = 'block';
}

//标题 重要程度 跟踪 关联文档附件
function _storePageObj(){
	pageS.subject = _$("#subject").value;
	pageS.importantLevel = _$("#importantLevel").value;
	pageS.canTrack = _$("#canTrack").value;
	pageS.fileS = pageX.fileComponent.attObjArray;
	pageS.summaryId = pageX.summary["id"];
	
	pageS.colArchiveName = _$("#colArchiveName").innerHTML;
	pageS.colPigeonhole = _$("#colPigeonhole").value;
	pageS.prevArchiveId = _$("#prevArchiveId").value;
	pageS.archiveId = _$("#archiveId").value;
	pageS.content = _$("#content").value;
	
	pageS.cache = pageX.cache;
	
	cmp.storage.save(_storge_key, JSON.stringify(pageS), true);
	return;
}

//数据加载
function _initPageData() {
    
    //请求数据
    var summaryId = pageX.winParams["summaryId"] || "";
    var templateId = pageX.winParams["templateId"] || "";
    var subject = pageX.winParams["subject"] || "";
    var members = pageX.winParams.members || "";
    openFrom = pageX.winParams["openFrom"] || "";

    
  //修改图标
    if(!templateId){
        _$("#edit_receiver").innerHTML = '<span style="font-size: 24px;" class="cmp-icon iconfont see-icon-add-round"></span>';
    }
    
    var paramData = {
    		"summaryId" : summaryId,
    		"templateId" : templateId, 
    		"openFrom" : openFrom,
    		"subject" : subject,
    		"members" : members };

    //注册缓加载
    _registLazy();
    
	$s.Coll.newColl({}, paramData, errorBuilder({
        success : function(result) {
            pageX.isInitData = true;
        	_fillPage(result);
        },
        alertFn : function(){
            cmp.dialog.loading(false);
            _$("#sendBtn").style.display = "none";
        }
    }));
    
}

//注册懒加载
function _registLazy(){
    
  //注册缓加载
    LazyUtil.addLazyStack({
        "code" : "lazy_cmp_form",
        "css" : [
                 _cmpPath + "/css/cmp-accDoc.css" + $verstion,
                 _cmpPath + "/css/cmp-selectOrg.css" + $verstion,
                 _cmpPath + "/css/cmp-att.css" + $verstion,
                 _cmpPath + "/css/cmp-picker.css" + $verstion,
                 _cmpPath + "/css/cmp-list.css" + $verstion
                 ],
        "js" : [
                _cmpPath + "/js/cmp-accDoc.js" + $verstion,
                _cmpPath + "/js/cmp-att.js" + $verstion,
                _cmpPath + "/js/cmp-lbs.js" + $verstion
                ]
    });
    
    LazyUtil.addLazyStack({
        "code" : "lazy_cmp",
        "css" : [
                 _cmpPath + "/css/cmp-listView.css" + $verstion,
                 _cmpPath + "/css/cmp-audio.css" + $verstion,
                 _cmpPath + "/css/cmp-search.css" + $verstion
                 ],
        "js" : [
                _cmpPath + "/js/cmp-flowV5.js" + $verstion,
                _cmpPath + "/js/cmp-listView.js" + $verstion,
                _cmpPath + "/js/cmp-imgCache.js" + $verstion,
                _cmpPath + "/js/cmp-app.js" + $verstion,
                _cmpPath + "/js/cmp-selectOrg.js" + $verstion,
                _cmpPath + "/js/cmp-picker.js" + $verstion,
                _cmpPath + "/js/cmp-dtPicker.js" + $verstion,
                _cmpPath + "/js/cmp-push.js" + $verstion,
                _cmpPath + "/js/cmp-audio.js" + $verstion,
                _cmpPath + "/js/cmp-server.js" + $verstion,
                _cmpPath + "/js/cmp-search.js" + $verstion,
                _cmpPath + "/js/cmp-popPicker.js" + $verstion,
                _cmpPath + "/js/cmp-handWriteSignature.js" + $verstion,
                _cmpPath + "/js/cmp-barcode.js" + $verstion,
                _cmpPath + "/js/cmp-camera.js" + $verstion
                ]
    });
    
    
  //添加懒加载数组
    LazyUtil.addLazyStack({
        "code" : "lazy_wf",
        "depend" : "lazy_cmp",
        "dependModel" : "strong",
        "css" : [_wfPath + "/css/wf.css" + $verstion],
        "js" : [_wfPath + "/js/wf.js" + $verstion,
                _cmpPath + "/js/cmp-zoom.js" + $verstion]
    });
    
  //添加懒加载数组
    LazyUtil.addLazyStack({
        "code" : "lazy_doc",
        "css" : [
                 _docPath + "/css/doc.css" + $verstion,
                 _docPath + "/css/docNewPigeonhole.css" + $verstion
                 ],
        "js" : [
                _docPath + "/js/docNewPigeonhole.js" + $verstion,
                _docPath + "/js/flexible.js" + $verstion
                ]
    });
    
  //添加懒加载数组
    LazyUtil.addLazyStack({
        "code" : "lazy_dee",
        "css" : [],
        "js" : [
                _deePath + "/js/formDevelopmentOfadv.js" + $verstion
                ]
    });
}

//初始化页面数据
function _fillPage(data){
	
    pageX.currentUser = data["currentUser"];
    pageX.summary = data["summary"];
    pageX.defPolicy = data["defPolicy"];
    pageX.cache.isLightForm = (data["isLightForm"] == "true");
    
	//载入缓存数据
    
    var _jsonX = null;
    var storgeVal = cmp.storage.get(_storge_key, true);
    if(storgeVal){
        _jsonX = JSON.parse(storgeVal);
        pageX.cache = _jsonX.cache;
        delete _jsonX.cache;
    }
    
    if(_jsonX != null){//赋值缓存对象
    	pageS = _jsonX;
    	data.attList = pageS.fileS;
    	if(pageS.summaryId){
    	    pageX.summary["id"] = pageS.summaryId; 
    	}
    }
    
    pageX.importLevelEnum = data["importEnum"];
    if(pageS.importantLevel){
    	var items = pageX.importLevelEnum["items"];
        for(var i = 0, len = items.length; i < len; i++){
        	if(items[i]["key"] == pageS.importantLevel){
        		pageX.importLevelEnum["defVal"]["key"] = items[i]["key"];
        		pageX.importLevelEnum["defVal"]["label"] = items[i]["label"];
        		break;
        	}
        }
    }
    
    if(pageS.content){
    	_$("#content").value = pageS.content;
    }
    
    _setImportValue({
        key : pageX.importLevelEnum["defVal"]["key"],
        name : pageX.importLevelEnum["defVal"]["label"]//非常重要
    });
    
    var continueUpload = true;
    //表单模板有初始化附件
    var initAtt = data.attList;
    var needClone = !!data.needClone;
    if(initAtt && initAtt.length > 0){
		var tempCount = initAtt.length;
	    var tempText = "";
	    if(tempCount > 0){
	        tempText = tempCount;
	    }
	    document.getElementById("attCount").innerHTML = tempText;
	    //附件图标有附件时显示蓝色
	    var attDom = document.querySelector("#attBtn span");
	    if(tempCount > 0 && attDom && !attDom.classList.contains("cmp-active")){
	    	attDom.classList.add("cmp-active");
	    }
//      if(!CollUtils.isCMPShell()){
//      continueUpload = false;
//  }
    }
    var newPolicy = data["newPolicy"];
    if(newPolicy.uploadAttachment || newPolicy.uploadRelDoc){
    	var showAuth;
		if(newPolicy.uploadAttachment && newPolicy.uploadRelDoc){
	    	showAuth = -1;
	    } else if(newPolicy.uploadAttachment){
	    	showAuth = 1;
	    } else if(newPolicy.uploadRelDoc){
	    	showAuth = 2;
	    }
	    //初始化附件组件
	    var initParam = {
			showAuth : showAuth,
			uploadId : "picture",
			handler : "#attBtn",
			initAttData : initAtt,
			needClone : needClone,
			continueUpload: continueUpload,
			selectFunc : function(fileArray){
			    var attArray = new Array();
				var assArray = new Array();
				for(var i = 0 ; i < fileArray.length ; i++){
					if(fileArray[i].attachment_fileType == "associated"){
						assArray.push(fileArray[i]);
					}else if(fileArray[i].attachment_fileType == "file"){
						attArray.push(fileArray[i]);
					}
				}
				var $attCount, $assCount;
				$attCount = _$("#attCount");
				$assCount = _$("#assCount");
				if($attCount){
				    $attCount.innerHTML = attArray.length;
				}
				if($assCount){
				    $assCount.innerHTML = assArray.length;
				}
			    //附件图标有附件时显示蓝色
			    var attDom = document.querySelector("#attBtn span");
			    if(fileArray.length > 0 && attDom && !attDom.classList.contains("cmp-active")){
			    	attDom.classList.add("cmp-active");
			    }
			}
		}
        pageX.fileComponent = new SeeyonAttachment({initParam : initParam});
	    
	    //微信端， 没有附件
//      if(!CollUtils.isCMPShell()){
//      var tempAttLi = document.getElementById("attachment");
//      var _count = document.getElementById("attCount").innerText;
//      if(tempAttLi && (_count=="" || parseInt(_count, 10) == 0)){
//          tempAttLi.remove();
//            //删掉附件容器以及计算textarea的位置
//            document.getElementById("attachment_wrap").remove();
//            document.getElementById('content').style.bottom = "0px";
//            _$(".cmp-content").style.bottom = "60px";
//      }
//  }
    }else{
        if (tempCount > 0) {
        	_$("#attBtn").remove();
        } else {
            var tempAttLi = document.getElementById("attachment");
            if(tempAttLi){
                tempAttLi.remove();
            }
        }
    }
    
    var _templateId = data["templateId"];
    var _formRightId = data["formRightId"];
    var _bodyType = data["bodyType"];
    
     //textarea高度
    _setContentAreaHeight();
    
    //正文
    pageX.contentDesigner = new ContentDesigner({
        current : "_currentDiv",//保存正文序号的容器
        mainbodyContainer : "mainbodyDataDiv_0",
        viewState : "1",//可编辑状态
        contentType : _bodyType,//正文类型
        moduleTemplateId : _templateId
    });
    
    // 设置值
    pageX.contentDesigner.setInputVal("createId", pageX.currentUser["id"]);
    pageX.contentDesigner.setInputVal("moduleId", pageX.summary["id"]);
    
    //语音机器人-协同内容传参
	//_$("#content").value = pageX.winParams["content"] =="" && typeof(pageS.content)=="undefined" ? "":pageS.content;
    if(typeof(pageS.content)=="undefined" && pageX.winParams["content"]!= 'undefined' && pageX.winParams["content"]){
    	_$("#content").value = pageX.winParams["content"];
    }else if(typeof(pageS.content) != "undefined" && pageS.content){
    	_$("#content").value = pageS.content;
    }else{
    	_$("#content").value  = "";
    }
    //设置colmaindata的值
    colMainDataDomain = _$("#colMainData");
    CollUtils.setDomainFieldVal(colMainDataDomain, "id", pageX.summary["id"]);
    if(pageS && pageS.subject){
    	pageX.summary["subject"] =  pageS.subject;
    }
    CollUtils.setDomainFieldVal(colMainDataDomain, "subject", pageX.summary["subject"]);
    CollUtils.setDomainFieldVal(colMainDataDomain, "DR", pageX.summary["dr"]);
    
    if(data["formTitle"]){
    	_$("#subject").disabled = "disabled";
    	pageX.hasColSubject = data["formTitle"];
    }
    //调用表单接口渲染
    if(_bodyType == '20'){
    	
        LazyUtil.addLazyStack({
            "code" : "lazy_vue",
            "groups" : "seeyon_form",
            "js" : [
                    _formPath + "/js/lib/vue/vue.js" + $verstion,
                    _common_v5_path + "/cmp-resources/project/js/projectAccountList.js" + $verstion
                    ],
        });
        LazyUtil.addLazyStack({
            "code" : "lazy_form",
            "depend" : "lazy_vue",
            "dependModel" : "strong",
            "groups" : "seeyon_form",
            "css" : [
                       _formPath + "/css/index.css" + $verstion
                     ],
            "js" : [
                    _formPath + "/js/dataService.js" + $verstion,
                    _formPath + "/js/sui.js" + $verstion,
                    _unflowform + "/unflowform_m_api.s3js" + $verstion,
                    _unflowform + "/js/deeFieldInit.js" + $verstion,
                    _common_v5_path + "/widget/SeeyonContent.js" + $verstion
                    ],
        });
        
        //启动加载表单
        LazyUtil.startLazy("seeyon_form");
        
    	_$("#preDiv").textContent = pageX.summary["subject"];
		_$("#subject").style.display = "none";
    	
    	var _moduleId;
    	_$("#content").style.display = "none";
    	_$("#tId").value = _templateId;
    	_moduleId = _templateId;
    	if(openFrom == 'listWaitSend'){
    		_moduleId = pageX.summary.id;
    		_$("#newBusiness").value = "0";
    		cttId = data["cttId"];
    		if(cttId){
    			document.querySelector("#mainbodyDataDiv_0").querySelector("#id").value= cttId;
    		}
    	}
    	_$("#bodyType").value = "20";
    	_$("#contentRightId").value = _formRightId;//保存待发会用到
    	
    	_$("#canForward").value = pageX.summary.canForward;
    	_$("#canModify").value = pageX.summary.canModify;
    	_$("#canEdit").value = pageX.summary.canEdit;
    	_$("#canEditAttachment").value = pageX.summary.canEditAttachment;
    	_$("#canArchive").value = pageX.summary.canArchive;
    	_$("#canScanCode").value = pageX.summary.canScanCode;
    	_$("#canSetSupervise").value = pageX.summary.canSetSupervise;
    	_$("#projectId").value = pageX.summary.projectId;
    	_$("#advancePigeonhole").value = pageX.summary.advancePigeonhole;
    	_$("#advanceRemind").value = pageX.summary.advanceRemind;
    	_$("#archiveId").value = pageX.summary.archiveId;
    	_$("#archiveName").value = pageX.summary.archiveName;
    	_$("#colArchiveName").innerHTML = pageX.summary.archiveAllName;
    	_$("#archiveAllName").value = pageX.summary.archiveAllName;
    	_$("#canMergeDeal").value = pageX.summary.canMergeDeal;
    	_$("#canAnyMerge").value = pageX.summary.canAnyMerge;
    	_$("#deadline").value = pageX.summary.deadline;
    	_$("#advanceRemind").value = pageX.summary.advanceRemind;
    	_$("#deadlineDatetime").value = pageX.summary.deadlineDatetime;
    	_$("#formParentid").value = pageX.summary.formParentid;
    	_$("#formOperationId").value = pageX.summary.formOperationId;
    	_$("#formAppid").value = pageX.summary.formAppid;
    	_$("#oldProcessId").value = pageX.summary.processId;
    	_$("#attachmentArchiveId").value = pageX.summary.attachmentArchiveId;
    	CollUtils.setDomainFieldVal("colMainData", "caseId", pageX.summary.caseId || "");
    	
    	_$("#trackType").value = data["trackType"];
    	_$("#zdgzry").value = data["zdgzry"];
    	
    	var contentConfig = {
                "target" : "contentDiv",
                "bodyType" : "20",
                "content" : _moduleId,
                "onload" : function (){
                    dealHeader();
                    _isContentInit = true;
            		cmp.dialog.loading(false);
                },
                "moduleType" : "1",
                "ext" : {
                    "isLightForm" : pageX.cache.isLightForm,
                    "rightId" : _formRightId,
                    "viewState" : '1',
                    "allowQRScan" : pageX.summary.canScanCode == '1' ? true : false,
                    "summaryId" : pageX.summary["id"]
                }
            }
    	
      //初始化正文
    	LazyUtil.addLoadedFn("lazy_form", function(){
    	    SeeyonContent.init(contentConfig);
    	    contentConfig = null;
        });
    	
    	 _$("#mainbodyDataDiv_0").style.display ='none';
    	 
    	 if(!pageX.cache.isLightForm){
             //切换成原表单
    	     var $contentDiv = _$("#contentDiv");
             $contentDiv.style.height = pageX.contentHeight + "px";
             $contentDiv.style.overflow = "hidden";
         }
    	 //引导
         //新建引导 获取本地缓存
         var isHit = cmp.storage.get("m3_v5_collaboration_new_summary_src_form_flag");
         if(!isHit || isHit != "true"){
             var hitEle, hitType;
             hitEle = _$("#src_form_view_hint");
             hitType = pageX.cache.isLightForm ? cmp.i18n("collaboration.page.lable.srcForm") : cmp.i18n("collaboration.page.lable.lightForm");
             _$("#src_form_view_hint_txt", false, hitEle).innerHTML = cmp.i18n("collaboration.page.lable.srcFormHit", [hitType])
             hitEle.classList.remove("display_none");
             hitEle.querySelector(".btn")
                   .addEventListener("tap", function(){
                       cmp.storage.save("m3_v5_collaboration_new_summary_src_form_flag","true");
                       hitEle.classList.add("display_none");
                   });
         }
         
         //切换原样表单
    	 LazyUtil.addLoadedFn("lazy_form", function(){
    	     var srcFormBtn = _$("#src_form_btn"); 
             srcFormBtn.classList.remove("display_none");
             srcFormBtn.addEventListener("tap", function(){
            	 var _hitType = !pageX.cache.isLightForm ? cmp.i18n("collaboration.page.lable.srcForm") : cmp.i18n("collaboration.page.lable.lightForm");
            	 _$("#src_form_view_hint_txt", false, _$("#src_form_view_hint")).innerHTML = cmp.i18n("collaboration.page.lable.srcFormHit", [_hitType]);
                 
		 if(pageS.isSubmitting){
    		       return; 
    		 }
		 
                 _isContentInit = false;
                 var $contentDiv = _$("#contentDiv");
                 if(pageX.cache.isLightForm){
                     //切换成原表单
                     $contentDiv.style.height = pageX.contentHeight + "px";
                     $contentDiv.style.overflow = "hidden";
                 }else{
                     //切换成轻表单
                     $contentDiv.style.height = "auto";
                     $contentDiv.style.overflow = "auto";
                 }
                 
                 SeeyonContent.instance("contentDiv").loadForm("0", {
                     isLightForm : !pageX.cache.isLightForm,
                     loadCallback : function(){
                         _isContentInit = true;
                         pageX.cache.isLightForm = !pageX.cache.isLightForm;
                     }
                 });
             });
    	 });
    	 _$("#archive_li").style.display="";
    	 //OA-113003微协同调用没设置预归档的表单模板，在新建页面上无法设置预归档。
    	 if (pageX.summary.archiveAllName==null || pageX.summary.archiveAllName==""){
    	     if(newPolicy && newPolicy.pigeonhole){
    	    	 if(pageX.summary.archiveName !=null && pageX.summary.archiveName!=""){
    	    		 //OA-113007微协同：待发编辑模板没设置预归档但是发起人设置了预归档的协同，预归档显示为空
    	    		 _$("#colArchiveName").innerHTML = pageX.summary.archiveName;
    	    	 }else{
    	    		 _$("#colArchiveName").innerHTML = cmp.i18n("collaboration.pighole.click");
    	    	 }
                 _$("#colArchiveName").addEventListener("tap", selectArchive);
             } 
    	 }
    }else{
        
        LazyUtil.addLazyStack({
            "code" : "lazy_form",
            "js" : [
                    _unflowform + "/unflowform_m_api.s3js" + $verstion,
                    _common_v5_path + "/cmp-resources/project/js/projectAccountList.js" + $verstion
                ]
        });
        
    	if(newPolicy && newPolicy.pigeonhole){
    		_$("#archive_li").style.display="";
    		_$("#colArchiveName").addEventListener("tap", selectArchive);
    	}else{//没权限时去掉预归档
    		//_$("#archive_li").remove();
    		hasPigeonholePolicy = false;
    	}
    	cmp.dialog.loading(false);
    	_isContentInit = true;
    }
    
    if(data["trackSend"]=="false" || (pageS && pageS.canTrack == '0')){//跟踪
        _$("#trackingBtn").classList.remove('cmp-active');
        _setTracking(false);
    }
    
    pageX.winParams["templateId"] = _templateId;
    
    var tokenInputConfig = {
            target : "receiver_container",
            editable : false,
            names : null,
            layout : "auto",
            onChange : function(){
                _setContentAreaHeight();
            },
            onBlur : function(){
                _toggleReceiver("hide");
            },
            correntAccountId : pageX.currentUser["loginAccount"]
        }
    var wfNames = data.workflowNodeNames;
    if(wfNames){
        var c = "、";
        if(wfNames.indexOf(",") != -1){
            c = ",";
        }
        tokenInputConfig.names = data.workflowNodeNames.split(c);
    }
    if(!_templateId){
        tokenInputConfig.editable = true;
        tokenInputConfig.onChoose = function(u){
                                        pageX.inputUsers[u.id] = u;
                                    }
        tokenInputConfig.onDelete = function(id){
                                        //删除项
                                        if(id){
                                            delete pageX.inputUsers[id];
                                        }
                                    }
        tokenInputConfig.onDestroy = function(){
                                        delete pageX.inputUsers;
                                    }
    }
    
    //初始化数据
    if(data.receivers){
        tokenInputConfig.datas = data.receivers;
    }
    
    //需要在加载流程前初始化快速选人
    SeeyonTokeninput.init(tokenInputConfig);
    
    //切换显示
    _toggleReceiver(true);
    _$("#receiver_container_text").addEventListener("tap", function(e){
        
        e.stopPropagation();//不冒泡
        
        //展开接收人
        _toggleReceiver("show");
    });
    var rDom = _$("#receiver_container");
    rDom.style.height = "auto";
    rDom.style.overflowY = "auto";
 
    //启动缓加载
    LazyUtil.startLazy();
    
    setTimeout(function(){
        _initPage();
        _bindEvent();
    }, 50);
    
    if(_jsonX != null){//赋值缓存对象
    	_$("#subject").value = pageS.subject;
    	
        _$("#colArchiveName").innerHTML = pageS.colArchiveName;
        _$("#colPigeonhole").value = pageS.colPigeonhole;
        _$("#prevArchiveId").value = pageS.prevArchiveId;
        _$("#archiveId").value = pageS.archiveId;
    	
    	_M3_Remove_Storage();
    }else{//最后加载
    	if(_$("#bodyType").value != '20' && _$("#subject").value == '' && openFrom != 'listWaitSend'){
    		try{
    			var titleTip = cmp.i18n("collaboration.page.lable.pleaseInputContent");
        		if(titleTip.indexOf("[") > -1){
        			titleTip = cmp.i18n("collaboration.tip.text");
        		}
        		_$("#content").setAttribute("placeholder",titleTip);//请输入正文
        		_$("#subject").setAttribute("placeholder",cmp.i18n("collaboration.affairs.subject.maxLength"));
    		}catch(e){}
    	}
    }
    
    var _hasDocPlug = data["hasDocPlug"];
    if(!_hasDocPlug){
    	_$("#archive_li").style.display = "none";
    }
    
}

/**
 * 接收人效果切换
 */
function _toggleReceiver(p){
    
    var rText = _$("#receiver_container_text"), textDisplay, inputDisplay, showText = false;
    var DISPLAY_BLOCK = "inline-block", DISPLAY_NONE = "none";
    var text = SeeyonTokeninput.getNames();
    
    if(p == "hide"){
        showText = true;
    }else if(p == "show"){
        showText = false;
    }else{
        showText = rText.style.display == "none";
    }
    
    if(showText){
        textDisplay = DISPLAY_BLOCK;
        inputDisplay = DISPLAY_NONE;
        
        if(text){
            rText.innerText = text;
        }else{
            rText.innerHTML = "&nbsp;";
        }
    }else{
        textDisplay = DISPLAY_NONE;
        inputDisplay = DISPLAY_BLOCK;
    }
    
    if(rText.style.display == DISPLAY_BLOCK && textDisplay == DISPLAY_BLOCK){
        //没做变动
    }else{
        rText.style.display = textDisplay;
        _$("#receiver_container").style.display = inputDisplay;
        if(!showText){
            setTimeout(function(){
                SeeyonTokeninput.focus();
            }, 50);
        }
        
        //计算高度
        if(p !== true){
            _setContentAreaHeight();
        }
    }
}

//删除缓存数据
function _M3_Remove_Storage(){
	//cmp.storage.removeCacheData(_storge_key, true);
	cmp.storage.removeCacheData(_storge_key, true);
}


function _setContentAreaHeight(){
    
    //设置正文内容高度
    var perp = document.getElementById("colMainData").offsetHeight;
    document.getElementById("content").style.top = perp + "px";
    
    
  //优化渲染数度
    var headerH, headerDom = _$("#hid"), $attContenter = _$("#attachment_wrap");
   var hStyleHeight = headerDom.style.height;
   if(hStyleHeight){
       headerH = parseInt(hStyleHeight, 10);
   }else{
       headerH =  headerDom.offsetHeight;
   }
    
   pageX.contentHeight = pageX.windowHeight - headerH - perp - ($attContenter ? 40 : 0) - 50 - 10;
}

//页面展示
function _initPage(){
    
    var wfState = pageX.winParams["templateId"] ? "view" : "edit";
    var wfDesignerParam = {
            
            workflow : {
                moduleType : "1"
            },
            info : {
                state : wfState,
                defaultPolicyId : pageX.defPolicy["value"],
                defaultPolicyName : pageX.defPolicy["name"],
                currentAccountId : pageX.currentUser["loginAccount"],
                currentAccountName : pageX.currentUser["loginAccountName"],
                currentUserId : pageX.currentUser["id"],
                currentUserName : pageX.currentUser["name"],
                category : "collaboration",//分类 协同 collaboration
                workItemId : pageX.summary["affairWorkitemId"],
                affairId : pageX.summary["affairId"],
                bodyType : pageX.summary["bodyType"],
                activityId : pageX.summary["activityId"],
                formData : pageX.summary["formRecordId"],
                processTemplateId : pageX.summary["templateProcessId"],
                maxNameLength : -1,
                useTemplateId : true
            },
            onNodeChange : function(names){
                    
                //清空已经选择的人
                 SeeyonTokeninput.destroy();
                 
                 var rDom = _$("#receiver_container"); 
                 rDom.style.display = "inline-block";
                 //展示选择人
                 SeeyonTokeninput.showNames(names.split(","));
                 rDom.style.display = "none";
                 
                 //更新接收人
                 _toggleReceiver("hide");
             },
             getPermissions : function(callback){
                 var params = {"appName":"collaboration",
                          "defaultPolicyId":pageX.defPolicy.value};
                 //获取节点权限
                 $s.Coll.permissions({},params, errorBuilder({
                     success : function(ret){
                         callback(ret);
                     }
                 }))
             }
        };
    
    if(pageX.summary["processId"]
        && (!pageX.summary["templateId"] || pageX.summary["specialStepback"] === true)){
        wfDesignerParam.workflow.processId = pageX.summary["processId"];
    }
    if(pageX.summary["caseId"]){
        wfDesignerParam.workflow.caseId = pageX.summary["caseId"];
    }
    
    //流程
    LazyUtil.addLoadedFn("lazy_wf", function(){
        pageX.wfDesigner = new WorkFlowDesigner(wfDesignerParam);
        wfDesignerParam = null;
    });
}

//绑定事件
function _bindEvent(){
    
    _$("#sendBtn").addEventListener("tap", _send);
    
    //开关设置
    _$("#switch_pop_btn").addEventListener("tap", function(){
        _$("#setting_container").classList.toggle("display_none");
    });
    
  //影藏开关
    _$("#setting_container").addEventListener('tap', function(e){
        if(e.target == this){
            this.classList.toggle("display_none");
        }
    });
    
    cmp("#switchs_ul").on("tap", ".menu_btn", _clickMenuBtn);
    
  //开关按钮
    cmp("#switchs_ul .cmp-switch").each(function() { //循环所有toggle
        this.addEventListener('toggle', function(event) {
            var tCode = this.getAttribute("switchcode");
            _switch(tCode, this.classList.contains('cmp-active'));
        });
    });
    _bindWfEvent();

    //标题区两个事件
    _$("#subject").oninput = function() {
        _$("#preDiv").textContent = _$("#subject").value;
        _$("#subject").style.height = _$("#preDiv").offsetHeight + 'px';
        _setContentAreaHeight();
    }

    _$(".headline").addEventListener("tap",textToggle);

    
    //此处监听sui_form_customcontrol_render事件，当表单中自定义控件发生渲染时，会触发此事件
    document.addEventListener('sui_form_customcontrol_render', function(e){
    	_customcontrol_meetingroom_init(e);
    });
}

//开关事件
function _switch(code, isActive){
    if(code == "tracking"){//跟踪
        _setTracking(isActive);
    }
}

//单击菜单
function _clickMenuBtn(){
    
    _$("#setting_container").classList.toggle("display_none");
    
    var tCode = this.getAttribute("data-code");
    
    if(tCode == "ImportantLevel"){
        _setImportantLevel()
    }
}

//返回上一个页面
function _goBackAndRefresh(){
    _M3_Remove_Storage();
    
    //删除上个页面的缓存数据
    var deleCaches = pageX.winParams.preCaches || [];
    if(deleCaches.length > 0){
        for(var i = 0; i < deleCaches.length; i++){
            cmp.storage["delete"](deleCaches[i], true);
        }
    }
    
    var backIndex = pageX.winParams.backIndex;
    if(backIndex && backIndex > 0){
        cmp.href.back(backIndex + 1);
    }else{
        cmp.href.back();
    }
    
}

//->->->->->->->->->->->->->->->->->->->->->->->->->-> 提交逻辑 开始 ->

//检查流程
function _creatWorkflow(callback, drawWf){
    
  //流程
    if(pageX.inputUsers && !cmp.isEmptyObject(pageX.inputUsers)){
        
        var datas = [];
        for(var k in pageX.inputUsers){
            datas.push(pageX.inputUsers[k]);
        }
        
        //快速选人创建流程
        pageX.wfDesigner.createXML({
            jsonData : cmp.toJSON(datas),
            currentNodeId : "",
            drawWf : (drawWf === true),
            type : pageX.wfDesigner.FLOW_TYPE["concurrent"],
            callback : function(names, jsonData){
                callback();
            },
            errorCallback : function(result){
            	_stopSubmit();
            }
        });
    }else{
        callback();
    }
}

//发送 step-1
function _send(){
    if(!_isContentInit){
        _alert(cmp.i18n("collaboration.action.alert.contentinit"));
        return;
    }
    
    if(pageS.isSubmitting){
       return; 
    }
    
    _startSubmit();
    
    //协同发送前事件
    var eventParams={
    	funName : "beforSendColl",
    	data : null,
    	success : function(){
    		var p = {};
    	   	p.summaryId = pageX.summary["id"];
    	   	var newBusiness  =_$("#newBusiness").value ;
    	   	p.isNeedCheckAffair  =  newBusiness == "1" ? "false" : "true";
    	   	var templateId = pageX.summary["templateId"];
    	   	checkTemplateCanUse(templateId,function(){
    	   		$s.Coll.checkAffairAndLock4NewCol(p, errorBuilder({
        	        success : function(result) {
        	            if (result.success != 'true') {
        	                _stopSubmit();
        	                _alert(result["error_msg"]);
        	                return;
        	            }
        	            else {
        	                // 验证页面数据
        	                var checkRet = checkFields();

        	                if (checkRet) {
        	                    _creatWorkflow(function() {
        	                        _getContentDomain();
        	                    });
        	                }
        	            }
        	        },
        	        error : function(req) {
        	            _stopSubmit();
        	        }
        	    }));
    	   	},function(){
    	   		_stopSubmit();
    	   		return;
    	   	})
    	   	
    	},
    	error : function(){
    		_stopSubmit();
    	}
    }
    cmp.funProxy.getter(eventParams);
}

/*
 * 表单开发高级 : NC业务集成插件_001_表单开发高级 @param bodyType ：正文类型 @param affairId :affairId
 * @param attitude :态度 @param opinionContent ：意见内容 @param currentDialogWindowObj
 * ：当前Dialog对象
 */
function formDevelopAdance4ThirdParty(bodyType,affairId,attitude,opinionContent,currentDialogWindowObj,succesCallBack) {
  try{
      function failedCallBack(){
    	  _stopSubmit();
      }
      if(bodyType != '20' ){
          succesCallBack();
      }else {
          beforeSubmit(affairId, CollUtils.trim(attitude), CollUtils.trim(opinionContent),currentDialogWindowObj,succesCallBack,failedCallBack,null);
      }
   }catch(e){
       _stopSubmit();
	   _alert(cmp.i18n("collaboration.exception.formException"));
   } 
}
//正文验证及值域获取step-2
function _getContentDomain(){
    
    //正文验证
    pageX.contentDesigner.getContentDomains({
        checkNull : true,
        needCheckRule : true,
        allowQRScan : pageX.summary.canScanCode == '1' ? true : false,
        summaryId : pageX.summary["id"],
        domains : [],
        templateId : _$("#tId").value,
        rightId :_$("#contentRightId").value ,
        callback : function(backData){
        	var workflowPreFunc = function(){
        		var workflowCheckParam = {
	      		   event : "BeforeStart",
	      		   callback : function(flag){
	      			   if(flag){
	      				   //执行流程预提交
	      				   _preSubmit(backData["contentData"],backData['data']);
	      			   }else{
	      				 _stopSubmit();
	      			   }
	      		   },
	      		   formAppId : _$("#formAppid").value,
	      		   formId : "",
	      		   formOperationId : _$("#formOperationId").value
	             };
        		
        		//为了在工作流高级开发中能取到表单数据，所以这个地方需要将表单数据ID设置进流程参数。
                if (!pageX.wfDesigner.info.formData && _$("#bodyType").value == "20") {
                    pageX.wfDesigner.info.formData = backData["data"]["contentAll"]["contentDataId"];
                }
                
        		pageX.wfDesigner.executeWorkflowBeforeEvent(workflowCheckParam);
        	}
		    if(backData["result"] === true){
		    	if(_$("#bodyType").value == "20") {
	        		formDevelopAdance4ThirdParty(_$("#bodyType").value,backData.data.contentAll["contentDataId"],"start",_$("#contentRightId").value,null,workflowPreFunc);
	        	} else {
	        		workflowPreFunc();
	        	}
		    }else{
            	_stopSubmit();
        	}
        	
        }
    });
}

//流程预提交step-3
function _preSubmit(preDomains,data){
    
    var domains = preDomains || [];
  //  var currentWorkItemIsInSpecial = (affairSubState == '15' || affairSubState == '16' || affairSubState == '17');
    var _preSubmitCallBackFunc = function(preSubmitResult){
        if(preSubmitResult["result"] == "true"){
            
            //继续调用转圈
        	if(!hasloadingbar){
        		cmp.dialog.loading();
        	}
            
            //分逻辑 
            if(_$("#contentType").value == "20"){//表单
            	_submitFormContent(function(formSnMsg){
                    //保存正文后提交
                    _forSubmit(formSnMsg);
                });
            }else{
            	//预提交成功
                _submitContent(function(){
                    //保存正文后提交
                    _forSubmit();
                });
            }
        }else{
            _stopSubmit();
        }
    }
    

	    // 性能优化，表单需要执行预提交，自由协同不需要，协同模板不能在M3上发送
	if (_$("#contentType").value == "20") {// 表单
		var options = {
			"contentData" : domains,
			"onPop" : function() {
				// 组件层级管理，需要把这个影藏
				cmp.dialog.loading(false);
				hasloadingbar = false;
			},
			"callback" : _preSubmitCallBackFunc,
			"currentWorkItemIsInSpecial" : null,
			"formInfos" : data && data.contentAll//表单相关信息
		};

		pageX.wfDesigner.preSubmit(options);
	} else {

		var _paramObj = {};
		_paramObj["result"] = 'true';
		_preSubmitCallBackFunc(_paramObj);
	}
    
    
}

// 保存正文step-4
function _submitContent(successCallback){
    
    //var colMainDataDomain = _$("#colMainData");
    pageX.contentDesigner.setInputVal("title", CollUtils.filterUnreadableCode(colMainDataDomain.querySelector("#subject").value));
    
    //保存正文
    var params = {
            callback : function(saveBack){
                if(saveBack["success"] == "true"){
                    
                    var contentAll = saveBack["contentAll"];
                    
                    //设置协同相关数据
                    var colMainDataDomain = _$("#colMainData");
                    CollUtils.setDomainFieldVal(colMainDataDomain, "contentSaveId", contentAll["id"]);
                    CollUtils.setDomainFieldVal(colMainDataDomain, "contentZWID", contentAll["id"]);
                    
                    successCallback();
                }else{
                    _stopSubmit();
                }
            }
    }
    pageX.contentDesigner.saveOrUpdate(params);
}

function _submitFormContent(successCallback,operType){
	
	//表单正式提交
	var options = { 
			moduleId:_$("#id").value,
			needCheckRule:false,
			notSaveDB:false,
			rightId :_$("#contentRightId").value,
			allowQRScan : pageX.summary.canScanCode == '1' ? true : false,
		    summaryId : pageX.summary["id"],
		    templateId: _$("#tId").value,
		    needSn : (operType && "saveDraft" == operType) ? false : null 
	}
	cmp.sui.submit(options,function(err,data){
		if(err || data.success =="false"){
			_stopSubmit();
		}else{
		    
			 var contentAll = data.contentAll;
			   //var colMainDataDomain = _$("#colMainData");
			   CollUtils.setDomainFieldVal(colMainDataDomain, "contentSaveId", contentAll["id"]);
			   CollUtils.setDomainFieldVal(colMainDataDomain, "contentZWID", contentAll["id"]);
			   CollUtils.setDomainFieldVal(colMainDataDomain, "bodyType", "20");
			   CollUtils.setDomainFieldVal(colMainDataDomain, "formRecordid", contentAll["contentDataId"]);
			   CollUtils.setDomainFieldVal(colMainDataDomain, "contentTemplateId", contentAll["contentTemplateId"]);
			   CollUtils.setDomainFieldVal(colMainDataDomain, "contentDataId", contentAll["contentDataId"]);
			   successCallback(data.snMsg || "");
		}
	});
}


//提交数据了step-5
function _forSubmit(formSnMsg){
    
    //组装数据
    pageX.postData["colMainData"] = CollUtils.formPostData("colMainData");//协同数据
    pageX.postData = cmp.extend(pageX.postData, pageX.wfDesigner.getDatas());//流程数据
    
    //附件数据
    if(pageX.fileComponent){
    	pageX.postData.attFileDomain = pageX.fileComponent.getFileArray();
    }
    
    var p = {"_json_params" : cmp.toJSON(pageX.postData)}
    
    $s.Coll.send({}, p, errorBuilder({
        success : function(result) {
            if(result && result["error_msg"]){
                _stopSubmit();
                _alert(result["error_msg"]);//提示
            }else{
              	cmp.webViewListener.fire({ 
                	type: 'com.seeyon.m3.ListRefresh', 
                	data: {appId:"1"}
            	})
                
                if(formSnMsg){
                    _alert(formSnMsg, _goBackAndRefresh);
                }else{
                    //跳转到上个页面
                    _goBackAndRefresh();
                }
            }
        },
        error:function(req){
            _stopSubmit();
        }
    }));
}

//结束
function _stopSubmit(){
    cmp.dialog.loading(false);
    pageS.isSubmitting = false;
}

//开始提交
function _startSubmit(){
    pageS.isSubmitting = true;
    cmp.dialog.loading();//提交中...
}

//-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-< 提交逻辑 结束  <-

//=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》保存待发 开始 =》

//保存待发
function _saveDraft(){
    
    if(pageS.isSubmitting){
        return; 
    }
    //开始提交
    _startSubmit();
    
    //协同保存待发前事件
    var eventParams={
    	funName : "beforeSaveDraftColl",
    	data : null,
    	success : function(){
    		if(!_checkSubject()){
    	    	//_stopSubmit();
    	        return;
    	    }
    	    var p = {};
    	    p.summaryId = pageX.summary["id"];
    	    var newBusiness  =_$("#newBusiness").value ;
            p.isNeedCheckAffair  =  newBusiness == "1" ? "false" : "true";
            var templateId = pageX.summary["templateId"];
    	   	checkTemplateCanUse(templateId,function(){
    	   		$s.Coll.checkAffairAndLock4NewCol(p,errorBuilder({
        	        success : function(result) {
        	            if(result.success!='true'){
        	                _stopSubmit();
        	                _alert(result["error_msg"]);
        	                return;
        	            }
        	            else{
        	                //创建流程
        	                _creatWorkflow(function(){
        	                    var doSubmit = function(formSnMsg){
        	                        //数据设置
        	                          //var colMainDataDomain = _$("#colMainData");
        	                          CollUtils.setDomainFieldVal(colMainDataDomain, "id", pageX.summary["id"]);
        	                          
        	                          //组装数据
        	                          pageX.postData["colMainData"] = CollUtils.formPostData("colMainData");//协同数据
        	                          pageX.postData = cmp.extend(pageX.postData, pageX.wfDesigner.getDatas());//流程数据
        	                          
        	                          //附件数据
        	                          if(pageX.fileComponent){
        	                              pageX.postData.attFileDomain = pageX.fileComponent.getFileArray();
        	                          }
        	                          var p = {"_json_params" : cmp.toJSON(pageX.postData)}
        	                          
        	                          $s.Coll.saveDraft({}, p, errorBuilder({
        	                              
        	                              success : function(result) {
        	                                  if(result && result["error_msg"]){
        	                                      _stopSubmit();
        	                                      _alert(result["error_msg"]);//提示
        	                                  }else{
        	                                      if(formSnMsg){
        	                                          _alert(formSnMsg, _goBackAndRefresh);
        	                                      }else{
        	                                          //跳转到上个页面
        	                                          _goBackAndRefresh();
        	                                      }
        	                                  }
        	                              },
        	                              error:function(req){
        	                                  _stopSubmit();
        	                              }
        	                          }));
        	                    }
        	                    if(_$("#bodyType").value == "20"){
        	                        _submitFormContent(doSubmit,"saveDraft");
        	                    }else{
        	                        //保存正文后提交
        	                        _submitContent(doSubmit);
        	                    }
        	                });
        	   
        	            }        },
        	        error:function(req){
        	            _stopSubmit();
        	        }
        	    }));
    	   	},function(){
    	   		_stopSubmit();
    	   		return;
    	   	})
    	    
    	},
    	error : function(){
    		_stopSubmit();
    	}
    }
    cmp.funProxy.getter(eventParams);
}
//《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=《=保存待发 结束《=

//------------------ 流程编辑 开始 》》

//流程相关的事件
function _bindWfEvent(){
    
    //点击编辑流程
    cmp.event.click(_$('#edit_receiver'),function(){
       /* _creatWorkflow(function(){
            pageX.wfDesigner.edit();
        }, true);*/
        var fillMember = []
        if(pageX.inputUsers){
            for(var k in pageX.inputUsers){
                var m = pageX.inputUsers[k];
                fillMember.push({
                    id : m.id,
                    name : m.name,
                    type:"member"
                  });
            }
        }
        
        pageX.wfDesigner.edit({
            initMembers : fillMember
        });
    });
}

// ------------------ 流程编辑 结束 《《

// 验证字段
function checkFields(){
    
    if(!_checkSubject()){
        return false;
    }
    
    //流程
    if(pageX.wfDesigner.isWfEmpty() && (!pageX.inputUsers || cmp.isEmptyObject(pageX.inputUsers))){
        
        _stopSubmit();
        
        //流程不能为空！
        _alert(cmp.i18n("collaboration.page.dialog.wfNotNull"), function(){
               _toggleReceiver("show");
            });//提示
        return false;
    }
    
    return true;
}

//检查标题
function _checkSubject(){
 // 标题
    var $subject = _$("#subject");
    if(isValueBlank($subject)){
        //标题不能为空
    	var dom =document.querySelector("#subject");
    	
    	_stopSubmit();
    	
        _alert(cmp.i18n("collaboration.page.dialog.subjectNotNull"), 
        		function(){
        			dom.focus();
        		});//提示
    	return;
    }
    if(!pageX.hasColSubject && isOverMaxSize($subject,300)){
        
        _stopSubmit();
        
        //标题最大长度为85!
        _alert(cmp.i18n("collaboration.page.dialog.subject85Limit"));//提示
        return false;
    }
    return true;
}

//检查值是否未空
function isValueBlank(e){
    var ret = false;
    if(e && CollUtils.trim(e.value) == ""){
        ret = true;
    }
    return ret;
}

//检验最大长度
function isOverMaxSize(e, except){
    var ret = false;
    if(e){
        var v = e.value;
        if(v.length > except){
            ret = true;
        }
    }
    return ret;
}

//跟踪
function _setTracking(active){
    var trackValue = "0";
    if(active){
        trackValue = "1";
    }
    CollUtils.setDomainFieldVal("colMainData", "canTrack", trackValue);
}

//重要级别
function _setImportantLevel(){
    var btns = [];
    var items = pageX.importLevelEnum["items"];
    for(var i = 0, len = items.length; i < len; i++){
        btns.push({
            key : items[i]["key"],
            name : items[i]["label"]//非常重要
        });
    }
    cmp.dialog.actionSheet(btns, cmp.i18n("collaboration.page.lable.button.cancel"), function(item) {
        //点击操作
        _setImportValue(item);
    }, function() {
        //点击取消
    });
}

function _setImportValue(item){
  //点击操作
    var tempKey = item.key;
    var lable = item.name;
    CollUtils.setDomainFieldVal("colMainData", "importantLevel", tempKey);
    _$("#importLevelLable").innerText = lable;
}

//点击关闭
function _closePage(){
    
    if(!pageX.isInitData){
        //网络异常情况下，允许用户直接返回
        cmp.href.back();
    }else{
    	if(!pageS.isSubmitting){//发送的时候不能保存待发和放弃新建
    		var btns = [{
    			key : "saveDraft",
    			name : cmp.i18n("collaboration.page.lable.saveToDraft")//保存到待发
    		},{
    			key : "delete",
    			name : cmp.i18n("collaboration.page.lable.cancelCreat")//放弃新建
    		}];
    		cmp.dialog.actionSheet(btns, cmp.i18n("collaboration.page.lable.button.cancel"), function(item) {
    			
    			//点击操作
    			if("saveDraft" == item.key){
    				_saveDraft();
    			}else if("delete" == item.key){
    				//放弃新建的时候删除表单缓存
    				try{
    					_M3_Remove_Storage();
    					SeeyonContent.clearCache();
    					
    					if(_$("#bodyType").value == '20' && pageX.summary["formRecordId"]){
    						//清除后台缓存
    						$s.CapForm.removeSessionMasterDataBean(pageX.summary["formRecordId"],{}, errorBuilder({
    							success: function (ret) {}
    						}));
    					}
    				}catch(e){}
    				cmp.href.back();
    			}
    		}, function() {
    			//点击取消
    		});
    		
    	}
    }
}

//处理header定位问题
function dealHeader(){
	setTimeout(function(){
		cmp.HeaderFixed("#hid", document.querySelectorAll("#content, #subject, .sui-form-ctrl-value"));
		cmp.description.init(document.querySelector("#content"));
	}, 50);
}

//预归档
function selectArchive(){
	docPigehole4Col("",function (_result){
		if(_result && _result.msg=="OK"){
			_$("#colArchiveName").innerHTML = _result.name;
			_$("#colPigeonhole").value = _result.id;
			_$("#prevArchiveId").value = _result.id;
			_$("#archiveId").value = _result.id;
		}else{//取消
			_$("#colArchiveName").innerHTML = cmp.i18n("collaboration.pighole.click");
			_$("#colPigeonhole").value = "";
			_$("#prevArchiveId").value = "";
			_$("#archiveId").value = "";
		}
	});
}
//标题区两个方法
function textToggle(){
    if (_$("#preDiv").style.visibility == "visible") {
        _$("#preDiv").style.visibility = "hidden";
        _$("#preDiv").setAttribute('class','');
        _$("#subject").style.display = "block";
        _$("#subject").style.height = _$("#preDiv").offsetHeight +"px";
        _setContentAreaHeight();
        setTimeout(function(){
        	_$("#subject").focus();
        }, 50)
    }
}
function showDiv(){
    _$("#preDiv").style.visibility = "visible";
    _$("#subject").style.display = "none";
    _$("#preDiv").setAttribute('class','eclips');

    _initLayout();

    _setContentAreaHeight();
}

function checkTemplateCanUse(templateId,successCallBack,errorCallBack){
	if(!templateId){
		successCallBack();
	} else {
		var param = {};
		param["data"] = "0_"+templateId;
		$s.Coll.checkTemplateCanUse({},param, errorBuilder({
	        success : function(result) {
	            if (result.success == 'true') {
	            	successCallBack();
	            } else {
	            	errorCallBack();
	            	_alert(cmp.i18n("collaboration.alert.template.cannot.use"));
	            }
	        },
	        error : function(req) {
	        	errorCallBack();
	        }
	    }));
	}
}